package com.example.qqviewspringboot.controller;

import com.example.qqviewspringboot.data.Message;
import com.example.qqviewspringboot.dto.MessageDto;
import com.example.qqviewspringboot.service.MessageService;
import com.example.qqviewspringboot.websocket.MessageWebSocketHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/messages")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageWebSocketHandler webSocketHandler;

    @Autowired
    private ObjectMapper objectMapper; // 注入配置好的 ObjectMapper

    @Value("${media.storage.path}")
    private String mediaStoragePath;

    /**
     * 发送消息，包括文本和可选的媒体文件（图片或视频）
     */
    @PostMapping(value = "/send", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
    public ResponseEntity<Message> sendMessage(
            @RequestParam Long senderId,
            @RequestParam Long recipientId,
            @RequestParam(required = false) String content,
            @RequestParam(required = false) MultipartFile media
    ) {
        if (senderId == null || recipientId == null) {
            return ResponseEntity.badRequest().body(null); // 请求参数不合法，返回400
        }

        String mediaType = null;
        String mediaUrl = null;

        if (media != null && !media.isEmpty()) {
            try {
                // 生成唯一文件名，避免文件名冲突
                String originalFilename = media.getOriginalFilename();
                String fileExtension = "";
                if (originalFilename != null && originalFilename.contains(".")) {
                    fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
                }
                String filename = UUID.randomUUID().toString() + "_" + originalFilename;

                Path uploadPath = Paths.get(mediaStoragePath);

                // 确保上传目录存在
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }

                // 保存文件到指定路径
                Path filePath = uploadPath.resolve(filename);
                Files.copy(media.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

                mediaType = media.getContentType();
                // 构建媒体文件的 URL
                mediaUrl = "/uploads/" + filename;

                // 日志确认保存路径（可选）
                System.out.println("Saving media to: " + filePath.toAbsolutePath());

            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
            }
        }

        // 保存消息（包括媒体信息）
        Message savedMessage = messageService.saveAndNotifyMessage(senderId, recipientId, content, mediaType, mediaUrl);

        // 设置消息为来自当前用户
        savedMessage.setFromCurrentUser(true);

        // 尝试通过 WebSocket 发送消息
        try {
            if (webSocketHandler.isUserConnected(recipientId)) {
                // 构建包含媒体信息的消息 JSON
                String messageJson = convertMessageToJson(savedMessage);
                webSocketHandler.sendMessageToUser(recipientId, messageJson);

                // 更新消息状态为已推送（DELIVERED）
                savedMessage.setReadStatus(Message.ReadStatus.DELIVERED);
                messageService.updateMessageStatus(savedMessage);
            } else {
                return ResponseEntity.status(HttpStatus.ACCEPTED).body(savedMessage);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }

        return ResponseEntity.ok(savedMessage);
    }

    private String convertMessageToJson(Message message) {
        try {
            return objectMapper.writeValueAsString(message);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "{}"; // 返回空 JSON 对象
        }
    }

    @GetMapping("/history")
    public ResponseEntity<List<Message>> getHistoryMessages(
            @RequestParam Long userId,
            @RequestParam Long friendId) {
        List<Message> messages = messageService.getConversation(userId, friendId);
        return ResponseEntity.ok(messages);
    }

    @GetMapping("/unread")
    public ResponseEntity<List<Message>> getUnreadMessages(
            @RequestParam Long userId) {
        List<Message> unreadMessages = messageService.getUnreadMessages(userId);
        return ResponseEntity.ok(unreadMessages);
    }

    @PostMapping("/read")
    public ResponseEntity<Void> markMessagesAsRead(@RequestBody List<Long> messageIds) {
        messageService.markMessagesAsRead(messageIds);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/conversations")
    public ResponseEntity<List<Object[]>> getAllConversations(@RequestParam Long userId) {
        List<Object[]> conversations = messageService.getAllConversations(userId);
        return ResponseEntity.ok(conversations);
    }
}
